/**
 * Software License, Version 1.0
 * 
 * Copyright 2003 The Trustees of Indiana University.  All rights reserved.
 * 
 *
 *Redistribution and use in source and binary forms, with or without 
 *modification, are permitted provided that the following conditions are met:
 *
 *1) All redistributions of source code must retain the above copyright notice,
 * the list of authors in the original source code, this list of conditions and
 * the disclaimer listed in this license;
 *2) All redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the disclaimer listed in this license in
 * the documentation and/or other materials provided with the distribution;
 *3) Any documentation included with all redistributions must include the 
 * following acknowledgement:
 *
 *"This product includes software developed by the Community Grids Lab. For 
 * further information contact the Community Grids Lab at 
 * http://communitygrids.iu.edu/."
 *
 * Alternatively, this acknowledgement may appear in the software itself, and 
 * wherever such third-party acknowledgments normally appear.
 * 
 *4) The name Indiana University or Community Grids Lab or NaradaBrokering, 
 * shall not be used to endorse or promote products derived from this software 
 * without prior written permission from Indiana University.  For written 
 * permission, please contact the Advanced Research and Technology Institute 
 * ("ARTI") at 351 West 10th Street, Indianapolis, Indiana 46202.
 *5) Products derived from this software may not be called NaradaBrokering, 
 * nor may Indiana University or Community Grids Lab or NaradaBrokering appear
 * in their name, without prior written permission of ARTI.
 * 
 *
 * Indiana University provides no reassurances that the source code provided 
 * does not infringe the patent or any other intellectual property rights of 
 * any other entity.  Indiana University disclaims any liability to any 
 * recipient for claims brought by any other entity based on infringement of 
 * intellectual property rights or otherwise.  
 *
 *LICENSEE UNDERSTANDS THAT SOFTWARE IS PROVIDED "AS IS" FOR WHICH NO 
 *WARRANTIES AS TO CAPABILITIES OR ACCURACY ARE MADE. INDIANA UNIVERSITY GIVES
 *NO WARRANTIES AND MAKES NO REPRESENTATION THAT SOFTWARE IS FREE OF 
 *INFRINGEMENT OF THIRD PARTY PATENT, COPYRIGHT, OR OTHER PROPRIETARY RIGHTS. 
 *INDIANA UNIVERSITY MAKES NO WARRANTIES THAT SOFTWARE IS FREE FROM "BUGS", 
 *"VIRUSES", "TROJAN HORSES", "TRAP DOORS", "WORMS", OR OTHER HARMFUL CODE.  
 *LICENSEE ASSUMES THE ENTIRE RISK AS TO THE PERFORMANCE OF SOFTWARE AND/OR 
 *ASSOCIATED MATERIALS, AND TO THE PERFORMANCE AND VALIDITY OF INFORMATION 
 *GENERATED USING SOFTWARE.
 */
package cgl.narada.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

import cgl.narada.service.ServiceException;
import cgl.narada.util.ProgressIndicator;


public class FileSplitter {
  private int fragmentSize;
  private int lastFragmentSize;
  private int numOfFragments;
  private String largeFileLoc ;
  private String moduleName = "FileSplitter: ";
  public FileSplitter() {

  }
  
  public void initializeSplittingParams(Properties fragmentationProperties) 
    throws ServiceException {
    String fragmentSizeString = 
      fragmentationProperties.getProperty("fragmentSize"); 

    if (fragmentSizeString != null) {
      fragmentSize = Integer.parseInt(fragmentSizeString);
    }

    String numOfFragmentsString = 
      fragmentationProperties.getProperty("numberOfFragments"); 

    if (numOfFragmentsString != null) {
      numOfFragments = Integer.parseInt(numOfFragmentsString);
    }

    if (fragmentSize == 0 && numOfFragments == 0) {
      throw new ServiceException(moduleName + "Neither [fragmentSize] OR [" +
				 "numberOfFragments] specified correctly");
    }
    
    if (fragmentSize != 0 && numOfFragments != 0) {
      throw new ServiceException(moduleName + "Simultaneos specification of ["+
				 "fragmentSize] AND [numberOfFragments] is " +
				 "NOT allowed");
    }
    
    largeFileLoc = 
      fragmentationProperties.getProperty("fileLocation");
    if (largeFileLoc == null) {
      throw new ServiceException(moduleName + "The property fileLocation has "
				 + "not been specified ");		      
    }
    
    File largeFile = new File(largeFileLoc);
    
    if (  (!largeFile.exists()) || (!largeFile.isFile()) ) {
      throw new ServiceException(moduleName + "The specified file [" + 
				 largeFileLoc + 
				 "] does not exist. Please check " +
				 "specified file OR see if its a directory!");
    }
    
    long contentLength = largeFile.length();
    System.out.println(moduleName + "The specified file [" + largeFileLoc + 
		       "] is of length = " + contentLength);
    
    if (contentLength == 0) {
      throw new ServiceException(moduleName + "The file [" + largeFileLoc + 
				 "] has a contentLength of ZERO!");
    }
    
    /** Now that we have reached here, only one of either fragmentSize or
	numOfFragments WILL be non-zero */
    boolean shouldFragment = true;
    int remaining=0;
    int lastFragmentSize=0;
    
    if (fragmentSize != 0) {
      if (contentLength <= fragmentSize) {
	System.out.println(moduleName + "No fragmentation necessary  since " +
			   "contentLength=" + contentLength + 
			   " <= fragmentSize=" + fragmentSize);
	shouldFragment = false;
      } else {
	numOfFragments = (int) (contentLength/(long)fragmentSize );
	lastFragmentSize = fragmentSize;
	remaining = (int) ( contentLength - 
			    (long)(numOfFragments*fragmentSize) );
	if ( remaining != 0) {
	  numOfFragments++;
	  lastFragmentSize =  remaining;
	  System.out.println(moduleName + "LAST FRAGMENT SIZE = " + 
			     lastFragmentSize);
	}
      }
      
    } else {
      if (contentLength <= numOfFragments) {
	System.out.println(moduleName + "No fragmentation necessary since " +
			   "contentLength=" + contentLength + 
			   " <= numOfFragment" + numOfFragments);
	shouldFragment = false;
      } else {
	fragmentSize = (int) (contentLength/(long)numOfFragments );
	remaining = (int) ( contentLength - 
			    (long)(numOfFragments*fragmentSize) );
	lastFragmentSize = fragmentSize + remaining;
      }
    }
  }

  public void splitAndPublish() throws ServiceException {
    try {
      System.out.println(moduleName + "Will create and publish fragments");
      
      File largeFile = new File(largeFileLoc);
      String filename = largeFile.getName();
      FileInputStream fis = new FileInputStream(largeFile);
      long totalWritten=0;
    
      ProgressIndicator pi = new ProgressIndicator();
      long currCompletion = 0;
      long prevCompletion = 0;
      int bytesRead = 0;
      for (int i = 1; i < numOfFragments; i++) {
	controlMemoryUtilization();
	byte[] fragment = new byte[fragmentSize];
	bytesRead = fis.read(fragment);
	
	if (bytesRead != fragmentSize) {
	  System.out.println(moduleName + "Tried to read (" + fragmentSize + 
			     ") bytes, ended up reading (" + bytesRead + 
			     ") bytes!");
	}
	writeIndividualFragment(fragment);
	totalWritten += fragmentSize;
	double percentComplete =   
	  Math.floor ( (  ((double)i/(double)numOfFragments) * 100 ) );
	
	currCompletion = (long) percentComplete;
	pi.showUpdate(currCompletion, prevCompletion, 
		      " % of fragments created");
	prevCompletion = currCompletion;
      }

      byte[] fragment = new byte[lastFragmentSize];
      bytesRead = fis.read(fragment);
      if (bytesRead != fragmentSize) {
	System.out.println(moduleName + "Tried to read (" + fragmentSize + 
			   ") bytes, ended up reading (" + bytesRead + 
			   ") bytes!");
      }
      writeIndividualFragment(fragment);
      totalWritten += lastFragmentSize;

      fis.close();
      System.out.println(moduleName + "Total bytes written = " + totalWritten);
      
    } catch (IOException ioe) {
      throw new ServiceException(moduleName + 
				 "Error in createAndStoreFragments()->" + ioe);
    }

  }

  public void writeIndividualFragment(byte[] fragment){
    

  }

  private void controlMemoryUtilization() {
    long totalMemory=0;
    long UTIL_LIMIT = 45000000;

    totalMemory = Runtime.getRuntime().totalMemory();
    
    while (totalMemory > UTIL_LIMIT) {
      Thread _currentThread = Thread.currentThread();
      System.out.println(moduleName + "Will yield()->" + _currentThread + 
			 " to control Memory Utilization of [" + 
			 totalMemory*0.000001 + "] MBytes");
      Runtime.getRuntime().gc();
      _currentThread.yield();
      
      totalMemory = Runtime.getRuntime().totalMemory();
    }/* end while */

  }

}
